package my.mall.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    /** 秘钥 */
    static final String SECRET = "My-Token";
    /** 签名是有谁生成 */
    static final String ISSUSER = "My";
    /** 签名的主题  */
    static final String SUBJECT = "this is token";
    /** 签名的观众  */
    static final String AUDIENCE = "MINIAPP";

    static final Algorithm ALGORITHM = Algorithm.HMAC256(SECRET);

    public static String createToken(String username) {
        LocalDateTime expireDate = LocalDateTime.now().plusHours(2);
        Map<String, Object> map = new HashMap<>(2);
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        return JWT.create()
                // 设置头部信息 Header
                .withHeader(map)
                // 设置 载荷 Payload
                .withClaim("username", username)
                .withIssuer(ISSUSER)
                .withSubject(SUBJECT)
                .withAudience(AUDIENCE)
                // 生成签名的时间
                .withIssuedAt(new Date())
                // 签名过期的时间
                .withExpiresAt(DateUtils.asDate(expireDate))
                // 签名 Signature
                .sign(ALGORITHM);
    }

    public static String verifyTokenAndGetUsername(String token) {
        JWTVerifier verifier = JWT.require(ALGORITHM)
                .withIssuer(ISSUSER)
                .build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        Claim claim = claims.get("username");
        return claim.asString();
    }
}
